import { useCallback, useEffect, useRef, useState } from 'react'
import { message } from 'antd'
import type { StorageError } from '../../services/storage/types'

export interface AutoSaveConfig {
  delay?: number // 自动保存延迟（毫秒），默认3000
  maxRetries?: number // 最大重试次数，默认3
  enabled?: boolean // 是否启用自动保存，默认true
}

export enum SaveStatus {
  SAVED = 'saved', // 已保存
  SAVING = 'saving', // 保存中
  UNSAVED = 'unsaved', // 有未保存更改
  ERROR = 'error' // 保存失败
}

export interface AutoSaveState {
  status: SaveStatus
  lastSavedAt: Date | null
  error: StorageError | null
}

export interface AutoSaveReturn extends AutoSaveState {
  saveNow: () => Promise<void>
}

/**
 * 自动保存Hook
 * @param content 要监控的内容
 * @param saveFunction 保存函数
 * @param config 配置选项
 */
export function useAutoSave(
  content: string,
  saveFunction: () => Promise<void>,
  config: AutoSaveConfig = {}
): AutoSaveReturn {
  const { delay = 3000, maxRetries = 3, enabled = true } = config

  const [state, setState] = useState<AutoSaveState>({
    status: SaveStatus.SAVED,
    lastSavedAt: null,
    error: null
  })

  const saveTimerRef = useRef<NodeJS.Timeout | null>(null)
  const retryCountRef = useRef(0)
  const lastContentRef = useRef(content)
  const currentContentRef = useRef(content)
  const isSavingRef = useRef(false)
  const saveFunctionRef = useRef(saveFunction)

  // 更新content和saveFunction的ref
  useEffect(() => {
    currentContentRef.current = content
  }, [content])

  useEffect(() => {
    saveFunctionRef.current = saveFunction
  }, [saveFunction])

  // 执行保存操作
  const performSave = useCallback(async () => {
    // 防止并发保存
    if (isSavingRef.current) {
      console.log('[自动保存] 保存正在进行中，跳过')
      return
    }

    isSavingRef.current = true
    setState(prev => ({ ...prev, status: SaveStatus.SAVING, error: null }))

    try {
      await saveFunctionRef.current()

      setState({
        status: SaveStatus.SAVED,
        lastSavedAt: new Date(),
        error: null
      })

      retryCountRef.current = 0
      lastContentRef.current = currentContentRef.current

      console.log('[自动保存] 保存成功', new Date().toISOString())
    } catch (error) {
      console.error('[自动保存] 保存失败', error)

      // 重试逻辑
      if (retryCountRef.current < maxRetries) {
        retryCountRef.current++
        console.log(`[自动保存] 正在重试 (${retryCountRef.current}/${maxRetries})`)

        // 延迟后重试
        setTimeout(() => {
          isSavingRef.current = false
          performSave()
        }, 2000)
      } else {
        // 超过重试次数
        setState(prev => ({
          status: SaveStatus.ERROR,
          lastSavedAt: prev.lastSavedAt,
          error: error as StorageError
        }))

        message.error('自动保存失败，请手动保存文档')
      }
    } finally {
      if (retryCountRef.current === 0 || retryCountRef.current >= maxRetries) {
        isSavingRef.current = false
      }
    }
  }, [maxRetries])

  // 手动保存
  const saveNow = useCallback(async () => {
    // 取消自动保存计时器
    if (saveTimerRef.current) {
      clearTimeout(saveTimerRef.current)
      saveTimerRef.current = null
    }

    await performSave()
  }, [performSave])

  // 监听内容变化，触发自动保存
  useEffect(() => {
    if (!enabled) return

    // 内容未变化，不触发保存
    if (content === lastContentRef.current) return

    // 标记为未保存状态
    setState(prev => {
      // 如果正在保存，不改变状态
      if (prev.status === SaveStatus.SAVING) return prev
      return { ...prev, status: SaveStatus.UNSAVED }
    })

    // 清除之前的计时器
    if (saveTimerRef.current) {
      clearTimeout(saveTimerRef.current)
    }

    // 设置新的自动保存计时器
    saveTimerRef.current = setTimeout(() => {
      performSave()
    }, delay)

    // 清理函数
    return () => {
      if (saveTimerRef.current) {
        clearTimeout(saveTimerRef.current)
      }
    }
  }, [content, enabled, delay, performSave])

  // 组件卸载时清理
  useEffect(() => {
    return () => {
      if (saveTimerRef.current) {
        clearTimeout(saveTimerRef.current)
      }
    }
  }, [])

  return {
    ...state,
    saveNow
  }
}
